package com.lanxin.xx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanxin.xx.entity.XxDuanxiaoxi;
import com.lanxin.xx.entity.XxXiaoxijieshou;
import com.lanxin.xx.mapper.XxDuanxiaoxiMapper;
import com.lanxin.xx.mapper.XxXiaoxijieshouMapper;
import com.lanxin.xx.service.IXxDuanxiaoxiService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanxin.xx.vo.Duanxiaoxi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 短消息服务实现类
 * </p>
 *
 * @author zyq
 * @since 2025-07-26
 */
@Service
public class XxDuanxiaoxiServiceImpl extends ServiceImpl<XxDuanxiaoxiMapper, XxDuanxiaoxi> implements IXxDuanxiaoxiService {

    @Autowired
    private XxDuanxiaoxiMapper xxDuanxiaoxiMapper;

    @Autowired
    private XxXiaoxijieshouMapper xxXiaoxijieshouMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer sendMsg(XxDuanxiaoxi duanxiaoxi, List<Integer> eids) {
        // 1. 校验参数
        if (eids == null || eids.isEmpty()) {
            throw new IllegalArgumentException("接收人不能为空");
        }
        if (duanxiaoxi == null || duanxiaoxi.getBiaoti() == null || duanxiaoxi.getNeirong() == null) {
            throw new IllegalArgumentException("消息主题和内容不能为空");
        }

        // 2. 保存消息主表（XxDuanxiaoxi）
        int msgRow = xxDuanxiaoxiMapper.insert(duanxiaoxi);
        if (msgRow <= 0) {
            throw new RuntimeException("消息保存失败");
        }

        // 3. 获取自动生成的消息ID（mybatis-plus会自动回填主键）
        Integer xiaoxiId = duanxiaoxi.getOid();
        if (xiaoxiId == null) {
            throw new RuntimeException("消息ID生成失败");
        }

        // 4. 批量保存接收人关系（XxXiaoxijieshou）
        String isRead = "N"; // 初始状态：未读
        List<XxXiaoxijieshou> receiveList = new ArrayList<>();

        // 使用加强for循环遍历接收人ID列表
        for (Integer receiverId : eids) { // 遍历eids中的每个接收人ID
            XxXiaoxijieshou receive = new XxXiaoxijieshou();
            receive.setXiaoxiid(xiaoxiId); // 关联消息ID
            receive.setJieshouren(receiverId); // 当前循环到的接收人ID
            receive.setIsread(isRead); // 未读状态
            receiveList.add(receive); // 添加到集合
        }

        // 调用批量插入方法
        int receiveRow = xxXiaoxijieshouMapper.batchInsert(receiveList);
        if (receiveRow <= 0) {
            throw new RuntimeException("接收人关系保存失败");
        }

        return receiveRow; // 返回成功保存的接收人数量
    }

    //收件人是自己
    @Override
    public Page<Duanxiaoxi> listDuanxiaoxi(Page<Duanxiaoxi> page,
                                             String biaoti,
                                             String empName,
                                             LocalDate startDate,
                                             LocalDate endDate,
                                             Integer jieshouren) {

        QueryWrapper<Duanxiaoxi> wrapper = new QueryWrapper<>();
        if(biaoti!=null && !biaoti.isEmpty()){
            wrapper.like("x.biaoti",biaoti);
        }
        if(empName!=null && !empName.isEmpty()){
            wrapper.like("e2.empName",empName);
        }
        if(jieshouren!=null){
            wrapper.eq("xj.jieshouren",jieshouren);
        }
//        if(startDate!=null){
//           wrapper.apply("DATE(x.createDate) = DATE({0})", startDate);
//        }
//        if(endDate!=null){
//            wrapper.apply("DATE(x.createDate) = DATE({0})", endDate);
//        }


        if(startDate!=null && endDate!=null){
            wrapper.between("x.createDate", startDate, endDate);
        } else {
            if(startDate!=null){
                wrapper.ge("x.createDate", startDate);
            }
            if(endDate!=null){
                wrapper.le("x.createDate", endDate);
            }
        }

        //asc 升序 desc 降序
        wrapper.orderByDesc("x.createDate");
        return xxDuanxiaoxiMapper.listDuanxiaoxi(page,wrapper);
    }

    @Override
    public Duanxiaoxi getDuanxiaoxiById(Integer oid) {
        return xxDuanxiaoxiMapper.getDuanxiaoxiById(oid);
    }

    //发送人是自己
    @Override
    public Page<XxDuanxiaoxi> allMsg(Page<XxDuanxiaoxi> page,
                                     String biaoti,
                                     String empName,
                                     LocalDate startDate,
                                     LocalDate endDate,
                                     Integer creator) {
        QueryWrapper<XxDuanxiaoxi> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(biaoti)){
            wrapper.like("x.biaoti",biaoti);
        }
        if(StringUtils.isNotBlank(empName)){
            wrapper.like("e2.empName",empName);
        }
        if(creator!=null){
            wrapper.like("x.creator",creator);
        }
        if(startDate!=null && endDate!=null){
            wrapper.between("x.createDate", startDate, endDate);
        } else {
            if(startDate!=null){
                wrapper.ge("x.createDate", startDate);
            }
            if(endDate!=null){
                wrapper.le("x.createDate", endDate);
            }
        }

        //asc 升序 desc 降序
        wrapper.orderByDesc("x.createDate");
        return xxDuanxiaoxiMapper.allMsg(page,wrapper);
    }

    /**
     * 获取指定用户的最近N条短消息
     * @return 短消息列表
     */
    @Override
    public List<Duanxiaoxi> getRecentMsgs(Integer empOid, int limit) {
        // 关键修正：关联消息主表，按消息创建时间（createDate）排序
        // 1. 先通过关联查询获取当前用户收到的最新消息ID及主表时间
        List<Integer> msgIds = xxDuanxiaoxiMapper.getRecentMsgs(empOid, limit);

        // 2. 批量查询消息详情
        if (msgIds.isEmpty()) {
            return new ArrayList<>();
        }
        return xxDuanxiaoxiMapper.getDuanxiaoxiByIds(msgIds);
    }

}
